"""
三、改写之前用python实现的monitor.py 程序，在入口函数application中，根据url执行不同的响应函数

要点：

    1. 定义独立的响应函数
    2. 给url与响应函数做映射
    3. 在application中根据url获取响应函数
    4. 执行响应函数返回结果
"""

import subprocess as sub
from wsgiref.simple_server import make_server


def cpu():
    stdout = sub.getoutput('uptime')
    info = stdout.replace(',', '').split()[-3:]
    info = '1m: %s, 5m: %s, 15m: %s' % tuple(info)
    return [info.encode()]


def ram():
    stdout = sub.getoutput('free')
    info = stdout.splitlines()[1].split()[1:4]
    info = 'total: %s, used: %s, free: %s' % tuple(info)
    return [info.encode()]


def hd():
    stdout = sub.getoutput('df')
    return [stdout.encode()]


def app(env, response):
    path_info = env.get('PATH_INFO')

    # 判断是CPU，还是RAM，还是HD
    #
    # cpu: http://localhost:8080/monitor/cpu/
    # ram: http://localhost:8080/monitor/ram/
    # hd: http://localhost:8080/monitor/hd/
    #
    status = '200 OK'
    headers = [('Content-Type', 'text/plain')]

    if path_info == '/monitor/cpu/':
        body = cpu()
    elif path_info == '/monitor/ram/':
        body = ram()
    elif path_info == '/monitor/hd/':
        body = hd()
    else:
        status = '404 Not Found'
        body = [b'not found']
    response(status, headers)
    return body


if __name__ == '__main__':
    host = 'localhost'
    port = 8080
    server = make_server(host, port, app)
    server.serve_forever()
